<?php

namespace App\Listeners\Like;

use App\Common\Libs\Json;
use App\Consts\GlobalConst;
use App\Consts\GlobalCounterConst;
use App\Consts\GlobalMessageConst;
use App\Events\Like\CreateLikeEvent;
use App\Listeners\BaseListener;
use App\Models\UserMessageLikeReceive;
use Illuminate\Support\Facades\Log;

class CreateLikeListener extends BaseListener
{
    /**
     * Handle the event.
     *
     * @param CreateLikeEvent $event
     * @return bool
     */
    public function handle(CreateLikeEvent $event)
    {
        $this->saveFileLog(__CLASS__, $event);

        $msgLikeSend = $event->msgLikeSend;

        // 队列记录日志
        service()->LogCountService->createLogByQueue($event->logCountLoadData);

        // 【暂时】如果赞的是评论，要修改评论的<hot>
        if ($msgLikeSend['target_type'] == GlobalConst::TARGET_TYPE_COMMENT) {
            service()->CommentService->changeHotByQueue([
                'comment_id' => $msgLikeSend['target_id'],
                'trend' => $event->logCountLoadData['action_type'] == GlobalCounterConst::ACTION_TYPE_LIKE ?
                    GlobalCounterConst::INCREASE : GlobalCounterConst::DECREASE
            ]);
        }

        // 静态化【我收到的赞】
        if ($msgLikeSend['sender_id'] != $msgLikeSend['receive_id']) {
            Log::channel('event')->info('点赞静态化数据' . Json::encode(service()->MessageService->getLikeStaticMessageData($msgLikeSend)));
            // 更新被点赞用户的未读消息数
            service()->MessageService->changeUnreadCount([
                'user_id' => $msgLikeSend['receive_id'],
                'message_type' => GlobalMessageConst::COUNT_TYPE_LIKE,
                'count' => GlobalCounterConst::INCREASE
            ]);

            $receiveMsgId = UserMessageLikeReceive::getInstance($msgLikeSend['receive_id'])
                ->where('receive_id', $msgLikeSend['receive_id'])
                ->where('target_id', $msgLikeSend['target_id'])
                ->value('message_id');
            service()->MessageService->staticLikeMessage([
                'message_id' => $receiveMsgId,
                'sender_id' => $msgLikeSend['sender_id'],
                'receive_id' => $msgLikeSend['receive_id'],
                'target_id' => $msgLikeSend['target_id'],
                'created_at' => $msgLikeSend['created_at'],
                'static_message' => service()->MessageService->getLikeStaticMessageData($msgLikeSend)
            ]);
        }

        return true;
    }
}
